package com.share.shareplatform.sharegoods.controller;



import com.share.shareplatform.pojo.Shop;
import com.share.shareplatform.pojo.User;
import com.share.shareplatform.pojo.exception.LogicException;
import com.share.shareplatform.sharegoods.service.ShopService;
import com.share.shareplatform.sharegoods.service.feign.UserService;
import com.share.shareplatform.sharegoods.service.impl.ShopServiceImpl;
import com.share.shareplatform.util.AuthorityUtil;
import com.share.shareplatform.util.Result;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/shop")
@Validated
public class ShopController {

    @Autowired
    private ShopService shopService;

    @Autowired
    private UserService userService;

    @Autowired
    private RestTemplate restTemplate;

    @ApiOperation(value="店铺添加",notes="必需字段：name\n可选字段：introduce\n额外说明：如果是超级管理员：需要额外指定userId字段")
    @PostMapping
    @PreAuthorize("hasAuthority('shopAdd')")
    @GlobalTransactional(name = "global_test",rollbackFor = Exception.class)
    public Result addOne(@RequestBody(required = false) @Validated Shop shop) throws LogicException {
        //初始化
        if (!AuthorityUtil.hasAuthorityUtil("ROLE_admin")) {
            //获取用户jwt中的id
            Long userId =AuthorityUtil.getUserId();
            Shop oldShop = shopService.findOneByUserId(userId);
            if(oldShop!=null){
                return Result.getInstance(505,"您已经拥有店铺，无法再创建");
            }
            //设置店铺的用户id
            shop.setUserId(userId);
        }else{
            if(shop.getUserId()==null){
                throw new LogicException("请指定用户id");
            }

            User user=Result.getResultValue(userService.findOneById(shop.getUserId()),"user",User.class);

            if(user==null){
                throw new LogicException("用户不存在");
            }
            Shop oldShop = shopService.findOneByUserId(shop.getUserId());
            if(oldShop!=null){
                return Result.getInstance(505,"该用户已经拥有店铺，无法再创建");
            }
        }

        //部分属性初始化

        Shop.setInit(shop);

        Shop one = shopService.findOneByName(shop.getName());
        if(one!=null){
            throw new LogicException("该店名已被使用");
        }
        shopService.addOne(shop);

        return Result.getInstance(200,"success");
    }

    @ApiOperation(value="店铺批量删除",notes = "其中ids为 'id-id-id' 这种类型的字符串")
    @DeleteMapping("/all/{ids}")
    @PreAuthorize("hasAuthority('shopSuper')")
    public Result deleteAllByIds(@PathVariable("ids") String ids){
        String[] stringIds=ids.split("-");
        ArrayList<Long> arrayList=new ArrayList<>();
        try{
            for(String id:stringIds){
                arrayList.add(Long.parseLong(id));
            }
        }catch (Exception e){
            return Result.getInstance(505,"商品类型编号不合法");
        }

        Integer integer = shopService.deleteAllByIds(arrayList.toArray(new Long[arrayList.size()]));
        if(integer==0){
            return Result.getInstance(505,"删除失败");
        }
        return Result.getInstance(200,"删除了 "+integer+" 条数据");
    }

    @ApiOperation(value="店铺修改",notes="必需字段：name\n可选字段：introduce\n额外说明：如果是超级管理员：需要额外指定userId字段")
    @PutMapping
    @PreAuthorize("hasAuthority('shopUpdate')")
    public Result updateOne(@RequestBody(required = false) @Validated Shop shop, HttpServletRequest httpServletRequest) throws LogicException {

        if (!AuthorityUtil.hasAuthorityUtil("ROLE_admin")) {
            //获取用户jwt中的id
            Long userId =AuthorityUtil.getUserId();
            Shop oldShop = shopService.findOneByUserId(userId);
            if(oldShop==null){
                return Result.getInstance(505,"您没有店铺，无法修改");
            }
            Shop.update(oldShop,shop);

            Shop one = shopService.findOneByName(oldShop.getName());
            if(one!=null){
                throw new LogicException("该店名已被使用");
            }
            shopService.updateOne(oldShop);
        }else{
            //管理员修改
            if(shop.getId()==null){
                return Result.getInstance(505,"请指定店铺id");
            }
            Shop oldShop=shopService.findOneById(shop.getId());
            if(oldShop==null){
                throw new LogicException("没有该店铺");
            }
            Shop.update(oldShop,shop);
            Shop one = shopService.findOneByName(oldShop.getName());
            if(one!=null){
                throw new LogicException("该店名已被使用");
            }
            shopService.updateOne(oldShop);
        }

        return Result.getInstance(200,"success");
    }

    @ApiOperation(value="店铺删除")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('shopSuper')")
    public Result deleteOneById(@PathVariable("id") Long id ){

        Integer flag = shopService.deleteOneById(id);
        if(flag==0){
            return Result.getInstance(505,"删除失败,该店铺不存在");
        }
        return Result.getInstance(200,"success");
    }


    @ApiOperation(value="店铺查询，按name")
    @GetMapping("/name/{name}")
    @PermitAll
    public Result findOneByName(@PathVariable("name")
                                    @NotBlank(message = "名称不能为空")
                                    @Length(max = 20,message = "名称太长") String name){


        Shop shop=shopService.findOneByName(name);

        if(shop==null){
            return Result.getInstance(505,"not found");
        }

        return Result.getInstance(200,"success").put("shop",shop);
    }

    @ApiOperation(value="店铺查询，按id")
    @GetMapping("/{id}")
    @PermitAll
    public Result findOneById(@PathVariable("id") Long id){

        Shop shop =shopService.findOneById(id);
        if(shop==null){
            return Result.getInstance(505,"not found");
        }

        return Result.getInstance(200,"success").put("shop",shop);
    }

    @ApiOperation(value="店铺查询，按userId")
    @GetMapping("/user/{id}")
    @PermitAll
    public Result findOneByUserId(@PathVariable("id") Long id){
        Shop shop = shopService.findOneByUserId(id);
        return Result.getInstance(200,"success").put("shop",shop);
    }

    @ApiOperation(value="店铺查询，按userId")
    @GetMapping("/test/{id}")
    @PermitAll
    public Result test(@PathVariable("id") Long id){

        Shop shop=new Shop();
        shop.setName("haha");
        ((ShopServiceImpl)shopService).test(shop);

        return Result.getInstance(200,"success").put("shop",shop);
    }


}
